/*============================================================================
#     FileName: myshell.c
#       Author: Huoty
#        Email: loveqing2013@foxmail.com
#    TencentQQ: 1346632121
#     HomePage: http://loveqing2013.blog.163.com/
#      Version: 0.0.1
#   CreateDate: 2014-02-26 10:35:35
#      History: 
#  Description: 命令解释。
============================================================================*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dtdef.h"
#include "list_handle.h"
#include "file_rw.h"
#include "myshell.h"
    

static char buf[512];

static char *getstr(void)
{
    printf("\t--> ");
    fgets(buf, sizeof(buf), stdin);

    return buf;
}

/* 去除从命令行提取的字符串尾多余的'\n' */
static char *del_newline(char *str)
{
    char *str_bp = str;
    int l = 0;

    while (*str_bp != '\0')
    {
        str_bp++;
        l++;
    }
    *(str+l-1) = '\0';

    return str;
}

static void startx(void)
{
    system("clear");
    printf("\t╔══════════════════════════════════════════════════════════════╗\n");
    printf("\t║                  .________________________.                  ║\n"); 
    printf("\t║                  | ______________________ |                  ║\n");
    printf("\t║                  | I                    I |                  ║\n");
    printf("\t║                  | I   快译通电子词典   I |                  ║\n");
    printf("\t║                  | I__________________ _I |                  ║\n");
    printf("\t║                  !________________________!                  ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║          欢迎使用快译通电子词典    当前版本：3.0.1           ║\n");
    printf("\t║    ------------------------------------------------------    ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║                        《 选项菜单 》                        ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║         1. 进入词典查询          2. 载入自定义词库           ║\n");
    printf("\t║         3. 创建二进制索引词库    4. 添加词条到用户词库       ║\n");
    printf("\t║         5. 查看帮助              6. 退出电子词典             ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║                                                              ║\n");
    printf("\t║               http://loveqing2013.blog.163.com/              ║\n");
    printf("\t║             版权所有 (C) COPYRIGHT HOUTY PRIVATE             ║\n");
    printf("\t╚══════════════════════════════════════════════════════════════╝\n");
}

static void word_find(void)
{
    system("clear");
    puts("\n======================== 单词查询 ========================");
    
    while (1)
    {
        puts("\n请输入要查询的单词：(输入 -q 返回)");
        if (strcmp("-q\n", getstr())  == 0)
            return;
        print_trans(buf);
    }
}

static void load_wb(void)
{
    int in;

    system("clear");
    puts("\n==================== 加载词库 ====================\n");
    puts("\n\t1. 载入文本词库 （此选项存在bug）");
    puts("\t2. 载入二进制索引词库\n");
    puts("\n--------------------------------------------------\n");
    puts("\n请选择要加载的词库类型：");

    in = atoi(getstr());
    while (in < 1 || in > 2)
    {
        puts("输入错误，请选择 1 或 2 ：");
        in = atoi(getstr());
    }
    char *s;
    switch (in)
    {
        case 1: destroy();  //每次重新加载词库之前先销毁到原有的词库
                puts("请输入你要加载词库的文件名：（*.txt）");
           //     if(txtf_rw(del_newline(getstr())) == -1)
                s =getstr();
                del_newline(s);
                if (txtf_rw(s) == -1 )
                {
                    binf_rw("dict.bin");  //如果加载失败就重新载入默认词库
                    puts("加载词库失败！");
                }
                else
                    puts("加载词库成功！");
                break;
        case 2: destroy();
                puts("请输入你要加载词库的文件名：（*.bin）");
                if(binf_rw(del_newline(getstr())) == -1)
                {
                    binf_rw("dict.bin");  //如果加载失败就重新载入默认词库
                    puts("加载词库失败！");
                }
                else
                    puts("加载词库成功！");
                break;
    }

    puts("\n--------------------------------- completed ------");
    puts("输入任意字符返回：");
    getstr();
}

static void get_binf(void)
{
    system("clear");
    puts("\n================= 生成二进制索引词库 =================\n");
    puts("请输入要生成的二进制索引词库的文件名：（*.bin）");
    if (create_binf(del_newline(getstr())) == -1)
        puts("\n*** 生成二进制索引词库失败！***");
    else
        puts("\n*** 生成二进制索引词库成功！***");

    puts("\n--------------------------------- completed ------");
    puts("输入任意字符返回：");
    getstr();
}

static void user_wb(void)
{
    FILE *fp;
    char fn[512];
    char str[512];
    char str_word[512];
    char str_trans[1024];
    int i = 1;

    system("clear");
    puts("\n=============== 向用户词库添加新的词条 ===============\n");
    puts("请输入用户词库的文件名：（默认为 usr_dict.txt ）");
    strcpy(fn, del_newline(getstr()));

    if ((fp = fopen(fn, "a")) == NULL)
    {
        perror("Error open file, in user_wb !");
        exit(-1);
    }

    while (1)
    {
        strcpy(str_word, "#");
        puts("请输入词条信息");
        puts("      word: ");
        strcpy(str_word, strcat(str_word, getstr()));
        fputs(str_word, fp);

        strcpy(str_trans, "trans:");
        while (i)
        {
            printf("    trans%d: （格式：词性. 词义，-1 结束输入）\n", i);
            strcpy(str, del_newline(getstr()));
            if (strcmp(str, "-1") == 0)
            {
                i = 0;  //结束循环
            }
            else
            {
                if (i == 1)
                {
                    strcpy(str_trans, strcat(str_trans, str));
                }
                else
                {
                strcpy(str_trans, strcat(str_trans, "@"));  //每个解释间用@分隔
                strcpy(str_trans, strcat(str_trans, str));
                }
                /* 最后一个单词需要加'\n'的问题未解决 */

                i++;
            }
        }
        fputs(str_trans, fp);
        puts("\n------------------ 添加成功 ------------------");
        puts("输入 c 继续添加, 输入其他任意字符返回：");
        if (strcmp("c\n", getstr()) != 0)
            break;
    }

    fclose(fp);
}

static void help_doc(void)
{
    system("clear");
    puts("\n===================== 帮助手册 =====================\n");

    if (readme_rw() == -1)
    {
        puts("帮助文档尚未建立 ! ");
    }

    puts("\n----------------------------------- completed --------");
    puts("输入任意字符返回：");
    getstr();
    
}

void show_gui(void)
{
    int in;

    while (1)
    {
        startx();

        puts("请输入您的选择：");
        in = atoi(getstr());
        while (in < 1 || in > 6)
        {
            puts("输入错误，请选择菜单 1~6 ：");
            in = atoi(getstr());
        }

        switch (in)
        {
            case 1: word_find();
                    break;
            case 2: load_wb();
                    break;
            case 3: get_binf();
                    break;
            case 4: user_wb();
                    break;
            case 5: help_doc();
                    break;
            case 6: destroy();
                    exit(-1);
                    break;
        }
    }
}

#ifdef DEBUG
/*************************************************************************
 * FuncName: main
 *    Input: None
 *   Output: None
 *  Val-Res: None
 *   Return: 0
 *    Brief: Main program body!
*************************************************************************/
int main(void)
{
	

    return 0;
}
#endif

/************************ (C) COPYRIGHT HOUTY PRIVATE ********END OF FILE****/

